package com.searchengine.service.impl;

import com.searchengine.entity.KeywordWeight;
import com.searchengine.entity.User;
import com.searchengine.repository.KeywordWeightRepository;
import com.searchengine.repository.UserRepository;
import com.searchengine.service.KeywordWeightService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 关键词权重服务实现类
 */
@Service
public class KeywordWeightServiceImpl implements KeywordWeightService {

    @Autowired
    private KeywordWeightRepository keywordWeightRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    @Transactional
    public KeywordWeight addKeywordWeight(Long userId, String keyword, BigDecimal weight, Date startTime, Date endTime) {
        // 验证用户是否存在
        Optional<User> userOptional = userRepository.findById(userId);
        if (!userOptional.isPresent()) {
            throw new RuntimeException("用户不存在");
        }

        // 验证时间范围
        if (startTime.after(endTime)) {
            throw new RuntimeException("开始时间不能晚于结束时间");
        }

        // 检查是否有时间重叠
        if (checkOverlap(userId, keyword, startTime, endTime, null)) {
            throw new RuntimeException("该关键词的时间范围与已有记录重叠");
        }

        // 创建关键词权重记录
        KeywordWeight keywordWeight = new KeywordWeight();
        keywordWeight.setUser(userOptional.get());
        keywordWeight.setKeyword(keyword);
        keywordWeight.setWeight(weight);
        keywordWeight.setStartTime(startTime);
        keywordWeight.setEndTime(endTime);

        return keywordWeightRepository.save(keywordWeight);
    }

    @Override
    @Transactional
    public KeywordWeight updateKeywordWeight(Long id, BigDecimal weight, Date endTime) {
        // 验证记录是否存在
        Optional<KeywordWeight> keywordWeightOptional = keywordWeightRepository.findById(id);
        if (!keywordWeightOptional.isPresent()) {
            throw new RuntimeException("关键词权重记录不存在");
        }

        KeywordWeight keywordWeight = keywordWeightOptional.get();

        // 如果更新结束时间，检查是否与其他记录重叠
        if (endTime != null && !endTime.equals(keywordWeight.getEndTime())) {
            if (checkOverlap(keywordWeight.getUser().getId(), keywordWeight.getKeyword(), 
                    keywordWeight.getStartTime(), endTime, id)) {
                throw new RuntimeException("该关键词的时间范围与已有记录重叠");
            }
            keywordWeight.setEndTime(endTime);
        }

        // 更新权重
        if (weight != null) {
            keywordWeight.setWeight(weight);
        }

        return keywordWeightRepository.save(keywordWeight);
    }

    @Override
    @Transactional
    public void deleteKeywordWeight(Long id) {
        Optional<KeywordWeight> keywordWeightOptional = keywordWeightRepository.findById(id);
        if (!keywordWeightOptional.isPresent()) {
            throw new RuntimeException("关键词权重记录不存在");
        }
        keywordWeightRepository.deleteById(id);
    }

    @Override
    public KeywordWeight getKeywordWeightById(Long id) {
        Optional<KeywordWeight> keywordWeightOptional = keywordWeightRepository.findById(id);
        if (!keywordWeightOptional.isPresent()) {
            throw new RuntimeException("关键词权重记录不存在");
        }
        return keywordWeightOptional.get();
    }

    @Override
    public List<KeywordWeight> getUserKeywordWeights(Long userId) {
        return keywordWeightRepository.findByUserId(userId);
    }

    @Override
    public List<KeywordWeight> getUserKeywordWeightByKeyword(Long userId, String keyword) {
        return keywordWeightRepository.findByUserIdAndKeyword(userId, keyword);
    }

    @Override
    public List<KeywordWeight> getCurrentKeywordWeights(String keyword) {
        Date now = new Date();
        return keywordWeightRepository.findByKeywordAndStartTimeLessThanEqualAndEndTimeGreaterThanEqual(
                keyword, now, now);
    }

    @Override
    public BigDecimal calculateTotalWeight(String keyword) {
        List<KeywordWeight> weights = getCurrentKeywordWeights(keyword);
        return weights.stream()
                .map(KeywordWeight::getWeight)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    @Override
    public boolean checkOverlap(Long userId, String keyword, Date startTime, Date endTime, Long excludeId) {
        List<KeywordWeight> existingWeights = keywordWeightRepository.findByUserIdAndKeyword(userId, keyword);
        
        for (KeywordWeight existing : existingWeights) {
            // 排除当前正在更新的记录
            if (excludeId != null && existing.getId().equals(excludeId)) {
                continue;
            }
            
            // 检查时间重叠
            // 重叠条件: 新开始时间 < 旧结束时间 且 新结束时间 > 旧开始时间
            if (startTime.before(existing.getEndTime()) && endTime.after(existing.getStartTime())) {
                return true;
            }
        }
        
        return false;
    }
}